package com.example.portablefortheelderlybackground.sevice.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.portablefortheelderlybackground.common.Constants;
import com.example.portablefortheelderlybackground.common.key.paramsKey;
import com.example.portablefortheelderlybackground.dto.scienceDto.scienceDto;
import com.example.portablefortheelderlybackground.mapper.lookHistoryMapper;
import com.example.portablefortheelderlybackground.pojo.history.lookHistory;
import com.example.portablefortheelderlybackground.pojo.userDetailImpl;
import com.example.portablefortheelderlybackground.sevice.lookHistoryService;
import com.example.portablefortheelderlybackground.sevice.scienceService;
import com.example.portablefortheelderlybackground.utils.CommonUtil;
import com.example.portablefortheelderlybackground.utils.Response;
import com.example.portablefortheelderlybackground.vo.historyVo.lookAtScienceViewVo;
import com.example.portablefortheelderlybackground.vo.historyVo.lookAtScienceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.example.portablefortheelderlybackground.Enum.Message.ReturnMessageEnum.*;

@Service
@Slf4j
public class lookHistoryServiceImpl extends ServiceImpl<lookHistoryMapper, lookHistory> implements lookHistoryService {
    private final scienceService scienceService;

    @Autowired
    public lookHistoryServiceImpl(scienceService scienceService) {
        this.scienceService = scienceService;
    }

    @Override
    @Transactional
    public Response<String> saveScienceHistory(List<lookAtScienceVo> lookAtScienceVo) {
        System.out.println(lookAtScienceVo);
        //list里实体id装填的是文章的id,将id赋值给paperId
        //从上下文中获取user实体
        //先进行json序列化
        userDetailImpl userDetail = (userDetailImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //再parse
        if (ObjectUtils.isEmpty(userDetail)) {
            return Response.error(SERVER_ERROR.getMessage(), SERVER_ERROR.getCode(), SERVER_ERROR.getMessage());
        }
        int flag = 0;
        LambdaQueryWrapper<lookHistory> queryWrapper = new LambdaQueryWrapper<>();
        for (lookAtScienceVo lookAtScience : lookAtScienceVo) {
            lookAtScience.setPaperId(lookAtScience.getId());
            //2.并将id置为空
            lookAtScience.setId(null);
            lookAtScience.setUserId(userDetail.getUser().getId());
            lookAtScience.setStatus(Constants.NOT_DELETE);
            lookAtScience.setLookTime(CommonUtil.ifAbsent(lookAtScience.getLookTime(), LocalDateTime.now()));
            //3.判断文章Id和userId是否存在,如果存在则更新观看时间
            queryWrapper.clear();
            queryWrapper.eq(lookHistory::getPaperId, lookAtScience.getPaperId()).eq(lookHistory::getUserId, lookAtScience.getUserId());
            if (baseMapper.selectCount(queryWrapper) > 0) {
                baseMapper.update(lookAtScience, queryWrapper);
                continue;
            }
            flag = baseMapper.insert(lookAtScience);
        }
        if (flag >= Constants.INSERT_SUCCESS) {
            return Response.success(SAVE_SUCCESS.getMessage(), SAVE_SUCCESS.getCode(), SAVE_SUCCESS.getMessage());
        }
        return Response.error(SERVER_ERROR.getMessage(), SERVER_ERROR.getCode(), SERVER_ERROR.getMessage());
    }

    @Override
    public Response<List<lookAtScienceViewVo>> queryScienceHistoryByUserId(String userId, Integer page, Integer pageSize) {
        //构建page
        page = CommonUtil.ifAbsent(page, Constants.DEFAULT_PAGE);
        pageSize = CommonUtil.ifAbsent(pageSize, Constants.DEFAULT_PAGESIZE);
        Page<lookHistory> pageParam = new Page<>(page, pageSize);
        LambdaQueryWrapper<lookHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(lookHistory::getUserId, userId).eq(lookHistory::getStatus, Constants.NOT_DELETE);
        List<lookHistory> lookHistoryList = baseMapper.selectPage(pageParam, queryWrapper).getRecords();
        //如果数据为空,则直接返回
        if (ObjectUtils.isEmpty(lookHistoryList)) return Response.status(null);
        //遍历拷贝属性
        List<lookAtScienceViewVo> lookAtScienceViewVoList = new ArrayList<>();
        for (lookHistory lookHistory : lookHistoryList) {
            lookAtScienceViewVo lookAtScienceViewVo = new lookAtScienceViewVo();
            BeanUtils.copyProperties(lookHistory, lookAtScienceViewVo);
            lookAtScienceViewVo.setLookTime(lookHistory.getLookTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            //设置文章id
            lookAtScienceViewVo.setId(lookHistory.getPaperId());
            //设置文章标题和图片
            Response<scienceDto> scienceById = scienceService.getScienceById(lookHistory.getPaperId());
            //设置标题
            lookAtScienceViewVo.setTitle(scienceById.data.getTitle());
            //设置图片
            lookAtScienceViewVo.setImages(Objects.requireNonNull(scienceById.data.getScienceImagesList()).get(0).getImages());
            lookAtScienceViewVoList.add(lookAtScienceViewVo);
        }
        return Response.status(lookAtScienceViewVoList);
    }

    @Override
    public Response<Boolean> deleteScienceHistory(String userId, String[] scienceIds) {
        LambdaUpdateWrapper<lookHistory> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(lookHistory::getUserId, userId).in(lookHistory::getPaperId, Arrays.asList(scienceIds));
        queryWrapper.set(lookHistory::getStatus, paramsKey.DONT_STATUS);
        int update = baseMapper.update(new lookHistory(), queryWrapper);
        if (update > paramsKey.NUM_ZERO) {
            return Response.status(true, DELETE_SUCCESS.getCode(), DELETE_SUCCESS.getMessage());
        }
        return Response.status(false, DELETE_ERROR.getCode(), DELETE_ERROR.getMessage());
    }

    @Override
    public Response<Boolean> deleteScienceByStatus() {
        LambdaQueryWrapper<lookHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(lookHistory::getStatus, paramsKey.DONT_STATUS);
        int delete = baseMapper.delete(queryWrapper);
        return Response.status(delete > paramsKey.NUM_ZERO);
    }
}
